<?php

namespace App\Listeners;

use App\Enums\AssetStatus;
use App\Enums\RightsType;
use App\Events\AssetCreated;
use App\Models\Asset;
use App\Models\AssetKey;
use App\Models\Product;

class AssetKeySubscriber
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
    }

    public function handleAssetCreated(AssetCreated $event)
    {
        $asset = $event->asset;
        $product = Product::query()->where('contract_address', $asset->contract_address)->first();
        if ($product->rights_type->is(RightsType::KEY())) {
            if (AssetKey::query()->where('asset_id', $asset->id)->count() > 0) {
                return;
            }
            // 创建权益兑换码
            $assetKey = new AssetKey();
            $assetKey->asset_id = $asset->id;
            $assetKey->key = 'BBT' . $this->randomKey($asset->id, 7);
            // 判断是否是转售资产
            $prevAsset = Asset::query()
                ->where('token_id', $asset->token_id)
                ->where('id', '!=', $asset->id)
                ->where('asset_status', AssetStatus::ON_SALE)
                ->orderByDesc('id')->first();
            if ($prevAsset && $prevAsset->asset_key) {
                $assetKey->prev_code = $prevAsset->asset_key->key;
            }
            $assetKey->save();
        }
    }

    public function subscribe($events)
    {
        $className = self::class;
        $events->listen(AssetCreated::class, "{$className}@handleAssetCreated");
    }

    private function randomKey($assetId, $length)
    {
        $keyAlphabet = 'ACDEFGHIJKLMNOPQRSUVWXYZ' . '0123456789';

        mt_srand($assetId);      // Call once. Good since $application_id is unique.

        $key = '';
        for ($i = 0; $i < $length; ++$i) {
            $key .= $keyAlphabet[mt_rand(0, strlen($keyAlphabet) - 1)];
        }

        return $key;
    }
}
